﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .texts-input {
        margin-top: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="search-box">
        <div class="layui-form texts-input" lay-filter="searchForm">
            <div class="layui-form-item" style="margin-bottom: 0;">
                <label class="layui-form-label">退货单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="returnNumber" name="returnNumber" placeholder="请输入退货单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">销售订单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="salesOrdersCode" name="salesOrdersCode" placeholder="请输入销售订单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">客户名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="customeName" name="customeName" placeholder="请输入客户名称" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">单据状态:</label>
                    <div class="layui-input-inline">
                        <select name="documentStatus" id="documentStatus">
                            <option value="">请选择单据状态</option>
                            <option value="1">草稿</option>
                            <option value="2">已确认</option>
                            <option value="3">审核中</option>
                            <option value="4">已审批</option>
                            <option value="5">已完成</option>
                            <option value="6">已拒绝</option>
                            <option value="7">已生成生产工单</option>
                        </select>
                    </div>
                    <button class="layui-btn layui-bg-blue" lay-submit lay-filter="searchBtn">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button class="layui-btn" onclick="editSelected()">
                        <i class="layui-icon layui-icon-edit"></i> 修改
                    </button>
                    <button type="button" class="layui-btn layui-bg-blue" onclick="openAddModal()"><i class="layui-icon layui-icon-addition"></i>新增</button>
                    <button class="layui-btn layui-bg-red" onclick="deleteSelected()"><i class="layui-icon &#xe640; layui-icon-delete"></i>批量删除</button>
                </div>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="lg" id="salesReturnsTable">
            <thead>
                <tr>
                    <th><input type="checkbox" id="selectAll" lay-filter="allChoose"></th>
                    <th>退货单编号</th>
                    <th>退货单名称</th>
                    <th>销售订单编号</th>
                    <th>客户名称</th>
                    <th>退货日期</th>
                    <th>退货仓库</th>
                    <th>单据状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>

    <!-- 新增销售退货模态框 -->
    <div id="addSalesReturnsModal" style="display: none; padding: 20px;">
        <iframe id="addSalesReturnsFrame" src="" frameborder="0" style="width: 100%; height: 600px;"></iframe>
    </div>

</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    layui.use(['layer', 'form', 'laypage'], function(){
        var layer = layui.layer;
        var form = layui.form;
        var laypage = layui.laypage;
        
        // 当前页码和每页数量
        var currentPage = 1;
        var pageSize = 10;
        var allData = []; // 存储所有数据用于前端分页
        var filteredData = []; // 存储过滤后的数据
        
        // 单据状态映射
        var statusMap = {
            1: '草稿',
            2: '已确认', 
            3: '审核中',
            4: '已审批',
            5: '已完成',
            6: '已拒绝',
            7: '已生成生产工单'
        };
        
        // 页面加载时获取数据
        $(document).ready(function() {
            loadSalesReturnsList();
        });
        
        // 加载销售退货列表
        function loadSalesReturnsList(searchParams = {}) {
            $.ajax({
                url: '/Warehousings/GetSalesReturns',
                type: 'GET',
                data: searchParams,
                success: function(response) {
                    console.log('API Response:', response);
                    allData = response || [];
                    filteredData = allData.slice(); // 复制数组
                    currentPage = 1; // 重置页码
                    renderTable();
                    renderPagination();
                },
                error: function(xhr, status, error) {
                    layer.msg('加载数据失败: ' + error, {icon: 2});
                    console.error('Error loading data:', error);
                    console.error('Response:', xhr.responseText);
                }
            });
        }
        
        // 渲染表格
        function renderTable() {
            var tbody = $('#tb');
            tbody.empty();
            
            // 计算当前页数据
            var startIndex = (currentPage - 1) * pageSize;
            var endIndex = startIndex + pageSize;
            var pageData = filteredData.slice(startIndex, endIndex);
            
            if (pageData.length === 0) {
                tbody.append('<tr><td colspan="9" style="text-align: center;">暂无数据</td></tr>');
                return;
            }
            
            pageData.forEach(function(item) {
                var returnDate = '';
                if (item.returnDate) {
                    try {
                        returnDate = new Date(item.returnDate).toLocaleDateString('zh-CN');
                    } catch(e) {
                        returnDate = item.returnDate;
                    }
                }
                var status = statusMap[item.documentStatus] || '未知状态';
                
                var row = `
                    <tr data-id="${item.id}">
                        <td><input type="checkbox" class="row-checkbox" value="${item.id}" lay-filter="rowCheck"></td>
                        <td>${item.returnNumber || ''}</td>
                        <td>${item.returnName || ''}</td>
                        <td>${item.salesOrdersCode || ''}</td>
                        <td>${item.customeName || ''}</td>
                        <td>${returnDate}</td>
                        <td>${item.returnsWarehouse || ''}</td>
                        <td>${status}</td>
                        <td>
                            <button class="layui-btn layui-btn-xs" onclick="editRow(${item.id})">编辑</button>
                            <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteRow(${item.id})">删除</button>
                            <button class="layui-btn layui-btn-xs layui-btn-normal" onclick="viewDetails(${item.id})">详情</button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
            
            // 重新渲染表单
            form.render('checkbox');
        }
        
        // 渲染分页
        function renderPagination() {
            if (filteredData.length === 0) {
                $('#pagination').empty();
                return;
            }
            
            laypage.render({
                elem: 'pagination',
                count: filteredData.length,
                limit: pageSize,
                curr: currentPage,
                layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                jump: function(obj, first) {
                    currentPage = obj.curr;
                    pageSize = obj.limit;
                    if (!first) {
                        renderTable();
                    }
                }
            });
        }
        
        // 搜索表单提交
        form.on('submit(searchBtn)', function(data) {
            var searchParams = {};
            
            if (data.field.returnNumber) {
                searchParams.ReturnNumber = data.field.returnNumber;
            }
            if (data.field.salesOrdersCode) {
                searchParams.SalesOrdersCode = data.field.salesOrdersCode;
            }
            if (data.field.customeName) {
                searchParams.CustomeName = data.field.customeName;
            }
            if (data.field.documentStatus) {
                searchParams.DocumentStatus = parseInt(data.field.documentStatus);
            }
            
            loadSalesReturnsList(searchParams);
            return false; // 阻止表单跳转
        });
        
        // 全选/取消全选
        form.on('checkbox(allChoose)', function(data) {
            var checked = data.elem.checked;
            $('.row-checkbox').each(function() {
                this.checked = checked;
            });
            form.render('checkbox');
        });
        
        // 行复选框点击
        form.on('checkbox(rowCheck)', function(data) {
            var allCheckboxes = $('.row-checkbox');
            var checkedCheckboxes = $('.row-checkbox:checked');
            $('#selectAll')[0].checked = allCheckboxes.length === checkedCheckboxes.length;
            form.render('checkbox');
        });
        
        // 重置表单
        window.resetForm = function() {
            $('#returnNumber').val('');
            $('#salesOrdersCode').val('');
            $('#customeName').val('');
            $('#documentStatus').val('');
            form.render('select');
            loadSalesReturnsList(); // 重新加载所有数据
        };
        
        // 全局函数：打开新增模态框
        window.openAddModal = function() {
            layer.open({
                type: 2,
                title: '添加产品销售退货单',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '80%'],
                content: '/Warehousings/AddSalesReturnsView',
                end: function() {
                    loadSalesReturnsList(); // 关闭模态框后刷新列表
                }
            });
        };
        
        // 编辑选中的记录
        window.editSelected = function() {
            var checkedIds = [];
            $('.row-checkbox:checked').each(function() {
                checkedIds.push($(this).val());
            });
            
            if (checkedIds.length === 0) {
                layer.msg('请选择要编辑的记录', {icon: 0});
                return;
            }
            
            if (checkedIds.length > 1) {
                layer.msg('只能选择一条记录进行编辑', {icon: 0});
                return;
            }
            
            editRow(checkedIds[0]);
        };
        
        // 编辑单行
        window.editRow = function(id) {
            layer.open({
                type: 2,
                title: '编辑销售退货单',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '80%'],
                content: '/Warehousings/UpdateSalesReturnsView?id=' + id
                // 移除end回调，避免重新加载整个列表
            });
        };

        // 更新表格中指定行的数据（供子窗口调用）
        window.updateTableRow = function(updatedData) {
            try {
                // 更新allData中的对应记录
                var dataIndex = allData.findIndex(item => item.id == updatedData.id);
                if (dataIndex !== -1) {
                    // 保持原有数据的位置，只更新内容
                    allData[dataIndex] = Object.assign(allData[dataIndex], {
                        returnNumber: updatedData.returnNumber,
                        returnName: updatedData.returnName,
                        salesOrdersCode: updatedData.salesOrdersCode,
                        customeCode: updatedData.customeCode,
                        customeName: updatedData.customeName,
                        returnDate: updatedData.returnDate,
                        returnsWarehouse: updatedData.returnsWarehouse,
                        documentStatus: updatedData.documentStatus,
                        reasonReturn: updatedData.reasonReturn
                    });
                }

                // 更新filteredData中的对应记录
                var filteredIndex = filteredData.findIndex(item => item.id == updatedData.id);
                if (filteredIndex !== -1) {
                    filteredData[filteredIndex] = allData[dataIndex];
                }

                // 重新渲染当前页面，保持分页位置
                renderTable();

                // 高亮显示更新的行（可选）
                setTimeout(function() {
                    var $row = $('tr[data-id="' + updatedData.id + '"]');
                    if ($row.length > 0) {
                        $row.addClass('layui-anim layui-anim-upbit');
                        $row.css('background-color', '#f2f9ff');
                        setTimeout(function() {
                            $row.css('background-color', '');
                        }, 2000);
                    }
                }, 100);

                console.log('表格行已更新，ID:', updatedData.id);
            } catch (error) {
                console.error('更新表格行失败:', error);
                // 如果更新失败，回退到重新加载
                loadSalesReturnsList();
            }
        };
        
        // 删除选中的记录
        window.deleteSelected = function() {
            var checkedIds = [];
            $('.row-checkbox:checked').each(function() {
                checkedIds.push(parseInt($(this).val()));
            });
            
            if (checkedIds.length === 0) {
                layer.msg('请选择要删除的记录', {icon: 0});
                return;
            }
            
            layer.confirm('确定要删除选中的 ' + checkedIds.length + ' 条记录吗？', {
                btn: ['确定', '取消']
            }, function(index) {
                // 批量删除
                $.ajax({
                    url: '/Warehousings/BatchDeleteSalesReturns',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(checkedIds),
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            layer.msg(response.message, {icon: 1});
                            // 移除已删除的记录，保持列表位置
                            removeBatchRecordsFromTable(checkedIds);
                            // 取消全选状态
                            $('#selectAll')[0].checked = false;
                            form.render('checkbox');
                        } else {
                            layer.msg(response.message, {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.msg('网络错误: ' + error, {icon: 2});
                        console.error('Batch delete error:', xhr.responseText);
                    }
                });
                
                layer.close(index);
            });
        };

        // 从表格中移除批量删除的记录
        function removeBatchRecordsFromTable(deletedIds) {
            try {
                // 从allData中移除记录
                allData = allData.filter(item => !deletedIds.includes(item.id));
                
                // 从filteredData中移除记录
                filteredData = filteredData.filter(item => !deletedIds.includes(item.id));
                
                // 检查当前页是否还有数据，如果没有且不是第一页，则回到上一页
                var totalPages = Math.ceil(filteredData.length / pageSize);
                if (currentPage > totalPages && totalPages > 0) {
                    currentPage = totalPages;
                }
                
                // 重新渲染表格和分页
                renderTable();
                renderPagination();
                
                console.log('批量删除完成，删除记录数:', deletedIds.length);
            } catch (error) {
                console.error('移除记录失败:', error);
                // 如果出错，重新加载列表
                loadSalesReturnsList();
            }
        }
        
        // 删除单行
        window.deleteRow = function(id) {
            layer.confirm('确定要删除这条记录吗？', {
                btn: ['确定', '取消']
            }, function(index) {
                $.ajax({
                    url: '/Warehousings/DeleteSalesReturns',
                    type: 'POST',
                    data: { id: id },
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            layer.msg(response.message, {icon: 1});
                            loadSalesReturnsList();
                        } else {
                            layer.msg(response.message, {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.msg('删除失败: ' + error, {icon: 2});
                    }
                });
                layer.close(index);
            });
        };
        
        // 查看详情
        window.viewDetails = function(id) {
            var item = allData.find(x => x.id == id);
            if (!item) {
                layer.msg('找不到记录详情', {icon: 2});
                return;
            }
            
            var returnDate = '';
            if (item.returnDate) {
                try {
                    returnDate = new Date(item.returnDate).toLocaleDateString('zh-CN');
                } catch(e) {
                    returnDate = item.returnDate;
                }
            }
            
            var content = `
                <div style="padding: 20px; line-height: 2;">
                    <p><strong>退货单编号：</strong>${item.returnNumber || ''}</p>
                    <p><strong>退货单名称：</strong>${item.returnName || ''}</p>
                    <p><strong>销售订单编号：</strong>${item.salesOrdersCode || ''}</p>
                    <p><strong>客户编号：</strong>${item.customeCode || ''}</p>
                    <p><strong>客户名称：</strong>${item.customeName || ''}</p>
                    <p><strong>退货日期：</strong>${returnDate}</p>
                    <p><strong>退货仓库：</strong>${item.returnsWarehouse || ''}</p>
                    <p><strong>单据状态：</strong>${statusMap[item.documentStatus] || '未知状态'}</p>
                    <p><strong>退货原因：</strong>${item.reasonReturn || ''}</p>
                </div>
            `;
            
            layer.open({
                type: 1,
                title: '销售退货详情',
                shadeClose: true,
                shade: 0.8,
                area: ['600px', '500px'],
                content: content
            });
        };
    });
</script>
